package com.example.wallpaperapp.ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.wallpaperapp.R;
import com.example.wallpaperapp.base.BaseActivity;
import com.example.wallpaperapp.bean.UserInfo;
import com.example.wallpaperapp.ihttps.RetrofitService;
import com.example.wallpaperapp.p.SignInPresent;
import com.example.wallpaperapp.p.SinInP;
import com.example.wallpaperapp.utils.PhoneNumberUtils;
import com.example.wallpaperapp.utils.ToastUtil;
import com.example.wallpaperapp.v.SininV;
import com.mob.tools.utils.ResHelper;
import com.mob.tools.utils.SharePrefrenceHelper;

import org.json.JSONObject;

import butterknife.BindView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.UserInterruptException;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class SignInActivity extends BaseActivity implements SininV ,View.OnClickListener{
    @BindView(R.id.phone_num)
    EditText phone_num;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.et_pwa)
    EditText et_pwa;
    @BindView(R.id.et_pwa2)
    EditText et_pwa2;
    @BindView(R.id.bt_sign)
    Button bt_sign;
    @BindView(R.id.get_code)
    TextView get_code;
    private SinInP sinInP;
    String a;
    private Handler handler;
    private EventHandler eventHandler;
    private int currentSecond;
    private static final int COUNTDOWN = 60;
    private SharePrefrenceHelper helper;
    private static final String KEY_START_TIME = "start_time";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        helper = new SharePrefrenceHelper(this);
        helper.open("sms_sp");
        eventHandler = new EventHandler() {
            public void afterEvent(final int event, final int result, final Object data) {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //提交验证成功，跳转成功页面，否则toast提示
                            if (result == SMSSDK.RESULT_COMPLETE) {
//                                ResultActivity.startActivityForResult(
//                                        VerifyActivity.this, REQUEST_CODE_VERIFY, true, "+" + currentPrefix + " " + etPhone.getText());
                                ToastUtil.makeText(SignInActivity.this,"验证成功");

                            } else {
                                processError(data);
                            }
                        }
                    });
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE || event == SMSSDK.EVENT_GET_VOICE_VERIFICATION_CODE) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result == SMSSDK.RESULT_COMPLETE) {
                                currentSecond = COUNTDOWN;
                                handler.sendEmptyMessage(0);
                                helper.putLong(KEY_START_TIME, System.currentTimeMillis());
                            } else {
                                if (data != null && (data instanceof UserInterruptException)) {
                                    // 由于此处是开发者自己决定要中断发送的，因此什么都不用做
                                    return;
                                }
                                processError(data);
                            }
                        }
                    });
                }
            }
        };
        SMSSDK.registerEventHandler(eventHandler);
    }
    private void processError(Object data) {
        int status = 0;
        // 根据服务器返回的网络错误，给toast提示
        try {
            ((Throwable) data).printStackTrace();
            Throwable throwable = (Throwable) data;

            JSONObject object = new JSONObject(
                    throwable.getMessage());
            String des = object.optString("detail");
            status = object.optInt("status");
            if (!TextUtils.isEmpty(des)) {
                ToastUtil.makeText(this,des);
                return;
            }
        } catch (Exception e) {
            Log.w(TAG, "", e);
        }
        // 如果木有找到资源，默认提示
        int resId = ResHelper.getStringRes(getApplicationContext(),
                "smsdemo_network_error");
        String netErrMsg = getApplicationContext().getResources().getString(resId);
        ToastUtil.makeText(this,netErrMsg);

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_signin;
    }

    @Override
    protected void initView() {
        get_code.setOnClickListener(this);
        phone_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //手机号输入大于5位，获取验证码按钮可点击
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                et_code.setEnabled(phone_num.getText() != null && phone_num.getText().length() > 5);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {
        Log.d(TAG, "initData: " + a);
        sinInP = new SignInPresent(this);
        bt_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                a = phone_num.getEditableText().toString().trim();
                //此方法将注册的数据传入后台
                sinInP.requestMsg();
            }
        });

    }


    @Override
    public int getUserName() {
        if (a.isEmpty()) {
            return 0;
        } else {
            return Integer.parseInt(a);
        }

    }

    @Override
    public String getPassword() {
        return et_pwa.getText().toString().trim();
    }

    @Override
    public void onFailed(String msg) {
        ToastUtil.makeText(this, msg);
    }

    @Override
    public void onSuccess(String msg) {
        ToastUtil.makeText(this, msg);
    }

    @Override
    public void result(UserInfo userInfo) {
        Log.d(TAG, "result: " + userInfo.toString());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.get_code:
                //判断手机号格式
                if (PhoneNumberUtils.judgePhoneNums(SignInActivity.this, phone_num.getText().toString().trim())) {
                    //启动倒计时
                    //PhoneNumberUtils.judgePhoneNums(SignInActivity.this, get_code, phone_num.getText().toString().trim());
                    //发送验证码
                    SMSSDK.getVerificationCode("86", phone_num.getText().toString().trim(), "1319972", null);
                }else {
                    ToastUtil.makeText(SignInActivity.this,"手机号输入有误");
                }
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}